<template>
  <div class="app-container">
    <el-form :model="formData"
             label-width="120px"
             label-position="left">
      <el-form-item label="标题">
        <el-input v-model="formData.title"> </el-input>
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="formData.cid"
                   style="width:500px;"
                   placeholder="请选择">
          <el-option v-for="item in categoryList"
                     :key="item.categoryId"
                     :label="item.categoryName"
                     :value="item.categoryId" />
        </el-select>
      </el-form-item>

      <el-form-item label="内容">
        <Tinymce v-model="formData.text"
                 :height="200" />
      </el-form-item>

      <el-form-item label="排序">
        <el-input type="number"
                  v-model="formData.order"> </el-input>
      </el-form-item>

    </el-form>
    <div class="submit-box">
      <el-button type="primary"
                 :loading="loading"
                 style="width: 200px;"
                 @click.native.prevent="doSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
import ElDragSelect from "@/components/DragSelect";
import Tinymce from "@/components/Tinymce";
import { create } from "@/api/article";
import { getAll } from "@/api/category";
import { errorMsg, successMsg } from "@/utils/my";

export default {
  components: {
    Tinymce,
    ElDragSelect
  },
  data () {
    return {
      loading: false,
      categoryList: [],
      formData: {
        title: '',
        cid: '',
        text: '',
        order: 0
      }
    };
  },
  created () {
    this.fetchCategoryList();
  },
  methods: {
    doSubmit () {
      let that = this;
      let d = that.formData;
      if (d.title.length <= 0) {
        return errorMsg("请输入文章标题");
      }
      if (d.cid.length <= 0) {
        return errorMsg("请选择文章分类");
      }
      if (d.text.length <= 0) {
        return errorMsg("请输入文章内容");
      }

      d.cid = d.cid.length <= 0 ? '' : d.cid.toString()
      d.order = d.order <= 0 ? 0 : parseInt(d.order)

      that.loading = true;
      create(that.formData).then(res => {
        that.loading = false;
        if (res.code != 20000) {
          return errorMsg(res.message);
        }
        successMsg(res.message);
        setTimeout(function () {
          that.$router.push({ path: "/admin/article/list" });
        }, 1500);
      });
    },
    fetchCategoryList () {
      const that = this;
      getAll({ name: that.formData.name }).then(
        res => {
          that.categoryList = res.data;
        }
      );
    }
  }
};
</script>

<style>
.submit-box {
  height: 50px;
  line-height: 50px;
  text-align: center;
  padding-right: 20px;
}
</style>
